import random
from datetime import datetime
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from web import models
from web.utils.bootstrip import BootstrapModelForm
from web.utils.pagination import Pagination


class OrderAddModelForm(BootstrapModelForm):
    class Meta:
        model = models.Order
        # fields = "__all__"
        exclude = ["oid", "admin"]


def order_list(request):
    """订单列表"""
    queryset = models.Order.objects.all().order_by('-id')

    page_object = Pagination(request, queryset)
    form = OrderAddModelForm()
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
        "form": form
    }
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_add(request):
    """新建订单"""
    form = OrderAddModelForm(data=request.POST)
    if form.is_valid():
        # 额外增加一些非用户输入值，而是自己按规则生成的
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))
        # 在session中获取管理员ID
        form.instance.admin_id = request.session["info"]["id"]
        # 保存到数据库
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})


def order_delete(request):
    """删除订单"""
    uid = request.GET.get('uid')
    exists = models.Order.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, "error": "数据不存在"})

    models.Order.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def order_detail(request):
    """根据ID获取订单详情"""
    uid = request.GET.get("uid")
    row_dict = models.Order.objects.filter(id=uid).values("title", "price", "status").first()
    if not row_dict:
        return JsonResponse({"status": False, "error": "数据不存在"})

    result = {
        "status": True,
        "data": row_dict
    }
    return JsonResponse(result)


@csrf_exempt
def order_edit(request):
    """编辑订单"""
    uid = request.GET.get("uid")
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status": False, "tips": "数据不存在"})

    form = OrderAddModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})
